package com.why.controller;

import com.alibaba.fastjson.JSON;
import com.why.pojo.Order;
import com.why.pojo.Product;
import com.why.pojo.User;
import com.why.pojo.UserAddress;
import com.why.service.OrderService;
import com.why.service.ProductService;
import com.why.service.UserAddressService;
import com.why.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
public class CarController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ProductService productService;

    @Autowired
    private UserAddressService userAddressService;

    @Autowired
    private OrderService orderService;

    //购物车商品列表
    @RequestMapping(value = "carprolist",produces = "application/json;charset=utf-8")
    public String carProList(HttpServletRequest request){
        User user = userData(request);
        Map<String, List> carMap = (HashMap)redisTemplate.opsForValue().get("car");
        if (carMap==null){
            carMap=new HashMap<String, List>();
        }
        List<Product> products = (List<Product>) carMap.get(user.getId().toString());
        int prices = 0;
        if (products!=null){
            for (Product product:products){
                Product sqlproduct = productService.selectByPrimaryKey(Integer.parseInt(product.getId()));
                prices+=(sqlproduct.getPrice()*product.getCarcount());
            }
        }

        Map<String,Object> param = new HashMap<>();
        param.put("products",products);
        param.put("prices",prices);
        return JSON.toJSONString(param);
    }

    //添加或减少购物车
    @RequestMapping(value = "caradd",produces = "application/json;charset=utf-8")
    public String carAdd(Integer productId,HttpServletRequest request,String direction,Integer addCount){
        User user = userData(request);
        //未登录返回
        if (user==null){
            return JSON.toJSONString("userEmpty");
        }
        //car Map
        Map<String, Object> listMap = (HashMap)redisTemplate.opsForValue().get("car");
        if (listMap==null){
            listMap = new HashMap<>();
        }
        //用户的购物车商品集合
        List<Product> carPro = (List<Product>)listMap.get(user.getId().toString());
        Product product = null;

        //购物车是否为空
        if (carPro!=null&&carPro.size()!=0){

            for (int i=0; i<carPro.size(); i++){
                product = carPro.get(i);


                //查询库存
                Product sqlProduct = productService.selectByPrimaryKey(productId);
                int sqlCount = sqlProduct.getStock();
                //是否为添加多个
                if (addCount==null || "".equals(addCount)){
                    addCount = 1;
                }


                //购物车没有该商品 新增一个商品
                if (i==carPro.size()-1&&Integer.parseInt(product.getId())!=productId){
                    product = productService.selectByPrimaryKey(productId);
                    if (addCount>sqlCount){
                        return JSON.toJSONString("shortage");
                    }else {
                        productService.updateStock(product.getStock()-addCount, product.getId());
                        product.setCarcount(addCount);
                        carPro.add(product);
                    }
                    break;
                }

                //购物车已有商品
                if (Integer.parseInt(product.getId())==productId){
                    if ("jian".equals(direction)){
                        //商品库存增加，购物车商品减少
                        productService.updateStock(sqlCount+1, sqlProduct.getId());
                        carPro.get(i).setCarcount(product.getCarcount()-1);
                    }else {
                        if (addCount>sqlCount){
                            return JSON.toJSONString("shortage");
                        }else {
                            productService.updateStock(sqlCount-addCount, sqlProduct.getId());
                            carPro.get(i).setCarcount(product.getCarcount()+addCount);
                        }
                    }
                    break;
                }
            }

        }
        else {//购物车为空
            carPro = new ArrayList<>();
            product = productService.selectByPrimaryKey(productId);

            //查询库存
            int sqlCount = product.getStock();
            //是否为添加多个
            if (addCount==null|| "".equals(addCount)){
                addCount = 1;
            }
            if (addCount>sqlCount){
                return JSON.toJSONString("shortage");
            }else {
                productService.updateStock(product.getStock()-addCount, product.getId());
                product.setCarcount(addCount);
                carPro.add(product);
            }
        }
        listMap.put(user.getId().toString(),carPro);
        redisTemplate.opsForValue().set("car",listMap);
        return JSON.toJSONString("success");
    }

    //添加到收藏
    @RequestMapping(value = "favoritesadd",produces = "application/json;charset=utf-8")
    public Object favoritesAdd(Integer productId,HttpServletRequest request){

        User user = userData(request);

        //未登录返回
        if (user==null){
            return JSON.toJSONString("userEmpty");
        }
        //favorites Map
        Map<String, Object> listMap = (HashMap)redisTemplate.opsForValue().get("favorites");

        if (listMap==null){//暂无任何收藏记录
            listMap = new HashMap<>();
        }
        //用户的商品收藏集合
        List<Product> favoritesPro = (List<Product>)listMap.get(user.getId().toString());
        Product product;
        if (favoritesPro!=null){
            if (favoritesPro.size()!=0){
                for (int i=0; i<favoritesPro.size(); i++){
                    product = favoritesPro.get(i);
                    if (Integer.parseInt(product.getId())==productId){
                        return JSON.toJSONString("exists");
                    }
                    //新增一个商品
                    if (i==favoritesPro.size()-1){
                        product = productService.selectByPrimaryKey(productId);
                        product.setCarcount(1);
                        favoritesPro.add(product);
                        break;
                    }
                }
            }else { //清空了收藏夹的老用户，再次添加
                product = productService.selectByPrimaryKey(productId);
                product.setCarcount(1);
                favoritesPro.add(product);
            }
        }else {//新用户暂无收藏记录
            favoritesPro = new ArrayList<>();
            product = productService.selectByPrimaryKey(productId);
            product.setCarcount(1);
            favoritesPro.add(product);
        }

        listMap.put(user.getId().toString(),favoritesPro);
        redisTemplate.opsForValue().set("favorites",listMap);
        return JSON.toJSONString("success");
    }

    //收藏列表
    @RequestMapping(value = "collectlist",produces = "application/json;charset=utf-8")
    public String collectList(HttpServletRequest request){
        User user = userData(request);
        Map<String, List> carMap = (HashMap)redisTemplate.opsForValue().get("favorites");
        List<Product> products=null;
        if (carMap==null){
            carMap=new HashMap<String, List>();
        }
        if (user!=null){
             products= (List<Product>) carMap.get(user.getId().toString());
        }
        if (products==null){
            products=new ArrayList<>();
        }
        return JSON.toJSONString(products);
    }

    //根据商品id删除收藏的商品
    @RequestMapping(value = "delfromcollect",produces = "application/json;charset=utf-8")
    public String delFromCollect(Integer productId,HttpServletRequest request,String direction){
        User user = userData(request);
        //favorites Map
        Map<String, Object> listMap = (HashMap)redisTemplate.opsForValue().get("favorites");
        if (listMap==null){
            listMap = new HashMap<>();
        }
        //用户的购物车商品集合
        List<Product> carPro = (List<Product>)listMap.get(user.getId().toString());
        Product product;
        for (int i=0; i<carPro.size(); i++){
            product = carPro.get(i);
            if (Integer.parseInt(product.getId())==productId){
                carPro.remove(i);
                break;
            }
        }
        listMap.put(user.getId().toString(),carPro);
        redisTemplate.opsForValue().set("favorites",listMap);
        return JSON.toJSONString("success");
    }


    //根据商品id删除购物车的商品
    @RequestMapping(value = "delprofromcar",produces = "application/json;charset=utf-8")
    public String delProFromCar(Integer productId,HttpServletRequest request,Integer carcount){
        User user = userData(request);
        //car Map
        Map<String, Object> listMap = (HashMap)redisTemplate.opsForValue().get("car");
        if (listMap==null){
            listMap = new HashMap<>();
        }
        //用户的购物车商品集合
        List<Product> carPro = (List<Product>)listMap.get(user.getId().toString());
        Product product;
        for (int i=0; i<carPro.size(); i++){
            product = carPro.get(i);
            if (Integer.parseInt(product.getId())==productId){
                carPro.remove(i);
                Product sqlProduct = productService.selectByPrimaryKey(productId);
                productService.updateStock(sqlProduct.getStock()+carcount,product.getId());
                break;
            }
        }
        listMap.put(user.getId().toString(),carPro);
        redisTemplate.opsForValue().set("car",listMap);
        return JSON.toJSONString("success");
    }

    //2加载用户信息
    @RequestMapping(value = "userinformation",produces = "application/json;charset=utf-8")
    public String userInformation(HttpServletRequest request){
        User user = userData(request);
        return JSON.toJSONString(user);
    }

    //2加载用户收件地址
    @RequestMapping(value = "addresslist",produces = "application/json;charset=utf-8")
    public String addressList(HttpServletRequest request){

        User user = userData(request);
        List<UserAddress> userAddressList = userAddressService.selectAddressByUserId(user.getId());

        return JSON.toJSONString(userAddressList);
    }

    //3新增订单并清空购物车
    @RequestMapping(value = "submitorder",produces = "application/json;charset=utf-8")
    public String submitOrder(HttpServletRequest request,Float prices,String address){

        User user = userData(request);
        Map<String, List> carMap = (HashMap)redisTemplate.opsForValue().get("car");
        List<Product> products = (List<Product>) carMap.get(user.getId().toString());

        Order order = new Order();
        for (int i=0;i<products.size();i++){
            Product product = productService.selectByPrimaryKey(Integer.parseInt(products.get(i).getId()));
            products.get(i).setPrice(product.getPrice());
        }
        order.setUserid(user.getId());
        order.setLoginname(user.getLoginname());
        order.setUseraddress(address);
        order.setCreatetime(new Date());
        order.setCost(prices);
        order.setSerialnumber(UUID.randomUUID().toString());
        order.setIsdelete(0);
        boolean result = orderService.addOrder(order,products);
        //car Map
        Map<String, Object> listMap = (HashMap)redisTemplate.opsForValue().get("car");
        if (listMap==null){
            listMap = new HashMap<>();
        }
        //清空购物车
        listMap.put(user.getId().toString(),null);
        redisTemplate.opsForValue().set("car",listMap);

        if (result){
            return JSON.toJSONString(order);
        }
        return "failed";

    }

    //清空我的收藏
    @RequestMapping("/clearCollect")
    public String clearCollect(HttpServletRequest request){
        User user = userData(request);
        HashMap<String,Object> favorites = (HashMap<String, Object>) redisTemplate.opsForValue().get("favorites");

        favorites.put(user.getId().toString(),null);

        redisTemplate.opsForValue().set("favorites",favorites);
        return "success";
    }

    //获取用户信息，用于本类调用
    public User userData(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        //redis
        User user = null;
        for(Cookie cookie : cookies){
            if (cookie.getName().equals("cookieUser")){
                HashMap<String,Object> map = (HashMap<String, Object>) redisTemplate.opsForValue().get(cookie.getValue());
                user = (User) map.get("user");
            }
        }
        return user;
    }
}
